﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using WCFMINERP.DAL;
using WCFMINERP.COM;
using System.IO;
using WCFMINERP.SharpZipLib;
using System.Xml;
using WCFMINERP.Contracts.InterFaces;
using System.Threading.Tasks;




namespace WCFMINERP.BLL.Analyse
{
    public class AnalyseBLL
    {
        Timer timeAnalyse = new Timer();
        bool _IsRunning = false;//控制是否运行
        string WorkFolder ="";///解压跟目录
       string DownLoadFolder="";//下载目录
       string SaveRootFolder = "";///保存订单的文件目录待拷贝的文件夹目录
                                  ///
    

        private delegate void NewTaskDelegate();

        public AnalyseBLL()
        {

            NewTaskDelegate task = timeAnalyse_Elapsed;
            IAsyncResult asyncResult = task.BeginInvoke(null, null);
            

            //System.Threading.Thread threa = new System.Threading.Thread(timeAnalyse_Elapsed);
            //threa.Start();
                      

            //System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(timeAnalyse_Elapsed));
            //t1.IsBackground = true;
            //t1.Start();

            //Task t1 = Task.Factory.StartNew(delegate { timeAnalyse_Elapsed(); });
            //t1.Wait();
            

           //执行开始调用          

           WorkFolder= CheckAutoOrderDir();
           DownLoadFolder = GetDownLoadForder();
           SaveRootFolder = GetOrderForder();
           string orderpath = GetOrderForder();
           //SaveRootFolder = orderpath + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
           //if (!Directory.Exists(SaveRootFolder))
           //{
           //    Directory.CreateDirectory(SaveRootFolder);
           //}

        }
        
        //void analyseOrder()
        //{
        //    timeAnalyse.Interval = 5000;
        //    timeAnalyse.Elapsed += new ElapsedEventHandler(timeAnalyse_Elapsed);                       
        //}
        bool _IsRuning = false;
        void timeAnalyse_Elapsed()
        {
            WriteAnalyseLog.WriteLogFile("开始自动解析订单");
            while (!_IsRuning)
            {
                _IsRuning = true;
                try
                {
                    //自动开单
                    int a = AnalyseOrder();
                    if (a == 0)
                    {
                       System.Threading.Thread.Sleep(5000);
                    }
                }
                catch (Exception ex)
                {
                    System.Threading.Thread.Sleep(5000);
                    WriteAnalyseLog.WriteLogFile(ex.Message);
                    _IsRuning = false;
                }
                _IsRuning = false;                
            }

            ////启动分析自动开单
            //if (!_IsRuning)
            //{
              
            //}
        }

        /// <summary>
        /// 获取自动开单目录
        /// </summary>
        /// <returns></returns>
        private string CheckAutoOrderDir()
        {
            string path = "";
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    FileDirPath fd = db.FileDirPath.FirstOrDefault(pt => pt.Des == "自动开单目录");
                    if (fd == null)
                    {
                        fd = new FileDirPath();
                        fd.Des = "自动开单目录";
                        FileDirPath fddeng = db.FileDirPath.FirstOrDefault(pt => pt.Des == "已开单");

                        string autoPath = fddeng.FileDir.Substring(0, fddeng.FileDir.LastIndexOf("\\") + 1) + "自动开单目录";
                        if (!Directory.Exists(autoPath))
                        {
                            Directory.CreateDirectory(autoPath);
                        }
                        db.AddToFileDirPath(fd);
                        path = fd.FileDir;
                        db.SaveChanges();
                    }
                    else
                    {
                        path = fd.FileDir;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return path;
        }

        /// <summary>
        /// 获取自动开单的目录
        /// </summary>
        /// <returns></returns>
        private string GetDownLoadForder()
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                return db.FileDirPath.FirstOrDefault(pt => pt.Des == "下载目录").FileDir;
            }
        }
        /// <summary>
        /// 获取已经开单的跟目录
        /// </summary>
        /// <returns></returns>
        private string GetOrderForder()
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                return db.FileDirPath.FirstOrDefault(pt => pt.Des == "已开单").FileDir;
            }
        }


        /// <summary>
        /// 自动开单
        /// </summary>
        /// <returns>0，等待，-1，错误，1，正常</returns>
        public int AnalyseOrder()
        {
            ///1从数据库获取到需要自动开单的记录
            ///2复制到操作目录并解压
            ///3读取XML信息
            ///4创建订单（包括移动照片）不需要后台服务中的移动照片，订单要审核
            ///如果解析出错的话出错列表
            int DoneStatus=(int)TransferStatus.Done;
           
            //_IsRunning = true;
            string OrderPath=SaveRootFolder;
            int uqid = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    //UploadQueue firstUploadQueue = new UploadQueue();
                    UploadQueue firstUploadQueue = db.UploadQueue.Where(ue => ue.Status == DoneStatus).OrderBy(or => or.CompleteTime).FirstOrDefault();
                    if (firstUploadQueue == null)
                    {
                        //_IsRunning = false;
                        return 0;//返回等待5秒重试
                    }
                    uqid = firstUploadQueue.UploadId;
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "获取到新的解析任务"));

                    string pahtSuffix=Path.GetExtension(firstUploadQueue.ShoptempPath);

                    string workZipPath = WorkFolder + "\\" + firstUploadQueue.ZipName;//移动后的文件名字

                    if (pahtSuffix.ToLower().EndsWith(".zip"))
                    {
                        workZipPath = workZipPath + ".zip";
                    }
                    if (pahtSuffix.ToLower().EndsWith(".rar"))
                    {
                        workZipPath = workZipPath + ".rar";
                    }
                    if (pahtSuffix.ToLower().EndsWith(".7z"))
                    {
                        workZipPath = workZipPath + ".7z";
                    }
                    string zipFilePath = DownLoadFolder + "\\" + firstUploadQueue.ZipName;
                    string zipBackFolder = DownLoadFolder.Substring(0, DownLoadFolder.LastIndexOf("\\") + 1) + "ZipBack";
                    if (!Directory.Exists(zipBackFolder))
                    {
                        Directory.CreateDirectory(zipBackFolder);
                    }
                    if (!File.Exists(zipFilePath + pahtSuffix))
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, firstUploadQueue.ZipName + "上传包未找到，请重新上传"));
                        firstUploadQueue.Remark += "err:上传包未找到，请重新上传";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();

                        return -1;
                    }
                    string backFilepath = zipBackFolder + "\\" + firstUploadQueue.ZipName + pahtSuffix;//备份文件目录
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在备份"));

                    FileOperate.CopyFileA(zipFilePath + pahtSuffix, backFilepath, 1);

                    bool isSecc = FileOperate.MoveFile(zipFilePath + pahtSuffix, workZipPath, 2);
                    if (!isSecc)//剪切不成功
                    {
                        bool isCopy = FileOperate.CopyAndDelFile(zipFilePath + pahtSuffix, workZipPath);
                        if (!isCopy)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "文件移动时出错，请检查是否有文件正在使用" + zipFilePath));
                            firstUploadQueue.Remark += "文件移动时出错，请检查是否有文件正在使用";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }

                        if (File.Exists(zipFilePath + pahtSuffix))
                        {
                            File.Delete(zipFilePath + pahtSuffix);
                        }
                    }

                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "文件拷贝到开单目录下成功，正在解压"));
                    //FileInfo workFile = new FileInfo(workFilePath);
                    string ZIPFolder = WorkFolder + "\\" + firstUploadQueue.ZipName;

                  //  UnZipClass.UnZip(workZipPath, ZIPFolder);//解压到文件夹下面

                    ZipHelp.WinrarUnZipPath(workZipPath, ZIPFolder);                                

                   // UnZipClass.ExtractZip(workZipPath, ZIPFolder);
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "解压文件成功，正在验证文件"));
                    DirectoryInfo workDiec = new DirectoryInfo(ZIPFolder);//解压完成后的文件夹
                    string anlyseXmlPath = ZIPFolder + "\\images.xml";
                    //string anlyseXmlPath = ZIPFolder + "\\images.xml";

                    if (!File.Exists(anlyseXmlPath))
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "Xml信息不存在，请重新上传或者选择手动开单"));
                        firstUploadQueue.Remark = "XML文件缺失，请通知客人重新上传或者手动开单";
                        //手动开单按钮点击自动拷贝到固定的文件夹下并吧状态写入手动开单
                        //firstUploadQueue.Status = (int)TransferStatus.XmlFileNoExists;
                        //firstUploadQueue.Remark += "";
                        db.SaveChanges();
                        return -1;
                    }
                    XmlDocument xml = new XmlDocument();
                    try
                    {
                        xml.Load(anlyseXmlPath);
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, firstUploadQueue.ZipName + "Xml信息打开失败。"));
                        firstUploadQueue.Remark = firstUploadQueue.ZipName + "Xml信息打开失败。" + ex.Message;
                        db.SaveChanges();
                        //如何处理待定
                        return -1;

                    }
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在读取订单信息"));
                    Tb_OrderBag newOrderBag = new Tb_OrderBag();
                    XmlNode xnOrderBag=null;
                    try
                    {
                        xnOrderBag = xml.SelectSingleNode(@"orderbag");
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now,EventType.Error,"XML缺少参数：orderbag属性"));

                        firstUploadQueue.Remark += "err:XML缺少参数：orderbag属性";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }
                    

                    //newOrderBag.BagName = xml.SelectNodes();
                    ///读取订单信息

                    XmlAttributeCollection orderbagXacList = xnOrderBag.Attributes;
                    int shopid = 0;
                    try
                    {
                        shopid = Convert.ToInt32(orderbagXacList["ShopId"].Value);
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：ShopId属性缺少或不正确"));
                        firstUploadQueue.Remark += "err:XML参数：ShopId属性缺少或不正确";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }

                    Shop currShop = db.Shop.FirstOrDefault(sh => sh.ShopId == shopid);
                    if (currShop == null)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "商户不存在"));
                        firstUploadQueue.Remark += "err:商户不存在";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }
                    newOrderBag.BagName = "";

                    try
                    {
                        var pNumAri = orderbagXacList["OrderID"];
                        if (pNumAri == null)
                        {
                            pNumAri = orderbagXacList["orderId"];
                            if (pNumAri == null)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderID属性缺少"));
                                firstUploadQueue.Remark += "err:XML参数：OrderID属性缺少";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            else
                            {

                            }
                        }
                        else
                        {

                        }
                        newOrderBag.BagName = pNumAri.Value;                        
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderID属性缺少"));
                        firstUploadQueue.Remark += "err:XML参数：OrderID属性缺少";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }

                    newOrderBag.EditUserID = 0;
                    //newOrderBag.FetchTime = Convert.ToDateTime(orderbagXacList["FetchTime"].Value);
                    //newOrderBag.OrderTime = Convert.ToDateTime(orderbagXacList["OrderTime"].Value);

                    
                    try
                    {
                        newOrderBag.OrderTime = DateTime.Now;// GetTime(orderbagXacList["OrderTime"].Value);
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderTime属性缺少或不正确"));
                        firstUploadQueue.Remark += "err:XML参数：OrderTime属性缺少或不正确";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }

                    try
                    {
                        //DateTime tech= newOrderBag.OrderTime.Add()

                        newOrderBag.FetchTime = DateTime.Now; // (orderbagXacList["FetchTime"].Value == "0") ? DateTime.Now : GetTime(orderbagXacList["FetchTime"].Value);

                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：FetchTime属性缺少或不正确"));
                        firstUploadQueue.Remark += "err:XML参数：FetchTime属性缺少或不正确";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }
                    newOrderBag.CompleteTime = DateTime.Now;
                    try
                    {
                        newOrderBag.Priority = Convert.ToInt32(orderbagXacList["Priority"].Value == "" ? "10" : orderbagXacList["Priority"].Value);
                        if (newOrderBag.Priority == 0)  //等于0也给10级
                        {
                            newOrderBag.Priority = 10;
                        }
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：Priority属性缺少或不正确"));
                        firstUploadQueue.Remark += "err:XML参数：Priority属性缺少或不正确";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }

                    try
                    {
                        newOrderBag.Remark = orderbagXacList["Remark"].Value.ToString();
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数1：Remark属性缺少或不正确"));
                        firstUploadQueue.Remark += "err:XML参数：Remark属性缺少或不正确";
                        firstUploadQueue.Status = (int)TransferStatus.Error;
                        db.SaveChanges();
                        return -1;
                    }
                    

                    newOrderBag.Shop = currShop;
                    newOrderBag.Status = (int)OrderBagStatus.AutoStartOrder;
                    newOrderBag.Type = (int)OrderBagType.RemoteOrder;
                    newOrderBag.users = db.users.FirstOrDefault();
                    newOrderBag.BagCode = "";                    
                    string ShopSaveCurrPath = SaveRootFolder + "\\" + currShop.shopName + "\\" + DateTime.Now.ToString("yyyy-MM-dd");//该商户今天的存放目录
                    if (!Directory.Exists(ShopSaveCurrPath))
                    {
                        Directory.CreateDirectory(ShopSaveCurrPath);
                    }
                    currShop.Shop_Product_Price.Load();
                    ///一下读取产品信息
                    XmlNodeList xmOrderList = xnOrderBag.ChildNodes;
                    foreach (XmlNode orderNode in xmOrderList)
                    {

                        XmlAttributeCollection orderInfoXacArray = orderNode.Attributes;
                        orderInfo neworder = new orderInfo();
                        //neworder.Area = Convert.ToDouble(orderInfoXacArray["Area"].Value);
                        neworder.CompleteTime = DateTime.Now;
                        string strCtmName="";
                        try
                        {
                            strCtmName = orderInfoXacArray["CtmName"].Value.ToString();
                            
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：CtmName属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：CtmName属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        neworder.CtmName = strCtmName;
                        try
                        {
                            neworder.Height = Convert.ToDouble(orderInfoXacArray["Height"].Value == "" ? "0" : orderInfoXacArray["Height"].Value);
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：Height属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：Height属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        string strOrderproductName = "";                       
                        try
                        {
                           strOrderproductName  = orderInfoXacArray["OrderProductName"].Value.ToString();
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderProductName属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：OrderProductName属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        neworder.isCount = 0;
                        neworder.OrderProductName = strOrderproductName;
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在提取产品 " + strOrderproductName + " 信息"));

                        neworder.OrderPath = "";
                        neworder.OrderType = (int)OrderInfoType.Normal;
                        string orderOrilPath = "";
                        try
                        {
                            orderOrilPath = WorkFolder + "\\" + firstUploadQueue.ZipName + "\\" + orderInfoXacArray["OrderPath"].Value;
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderPath属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：OrderPath属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }

                     

                        neworder.OrilOrderPath = orderOrilPath;                     

                        try
                        {
                            neworder.PageNum = Convert.ToInt32(orderInfoXacArray["PageNum"].Value == "" ? "0" : orderInfoXacArray["PageNum"].Value);
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：PageNum属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：PageNum属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }

                        

                        try
                        {
                            neworder.Priority = Convert.ToInt32(orderInfoXacArray["Priority"].Value == "" ? "10" : orderInfoXacArray["Priority"].Value);
                            if (neworder.Priority == 0)  //等于0也给10级
                            {
                                neworder.Priority = 10;
                            }
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品：Priority属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数产品：Priority属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        
                        try
                        {
                            var pNumAri =orderInfoXacArray["productNum"];
                            if (pNumAri==null)
                            {
                                pNumAri = orderInfoXacArray["ProductNum"];
                                if (pNumAri==null)
                                {
                                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：productNum属性缺少或不正确"));
                                    firstUploadQueue.Remark += "err:XML参数：productNum属性缺少或不正确";
                                    firstUploadQueue.Status = (int)TransferStatus.Error;
                                    db.SaveChanges();
                                    return -1;
                                }
                                else
                                {

                                }
                            }
                            else
                            {
 
                            }
                            neworder.productNum = Convert.ToInt32(pNumAri.Value);
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：productNum属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：productNum属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }

                        ///根据流程决定
                        neworder.ProductType = 0;
                        //try
                        //{
                        //    neworder.Remark = orderInfoXacArray["Remark"].Value;
                        //}
                        //catch (Exception ex)
                        //{
                        //    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数2：Remark属性缺少或不正确"));
                        //    firstUploadQueue.Remark += "err:XML参数：Remark属性缺少或不正确";
                        //    firstUploadQueue.Status = (int)TransferStatus.Error;
                        //    db.SaveChanges();
                        //    return -1;
                        //}
                        neworder.SinglePageNum = neworder.MultiPageNum = 0;
                        neworder.status = (int)OrderInfoStatus.AutoStartOrder;

                        int pid=0;
                        try
                        {
                           pid  = Convert.ToInt32(orderInfoXacArray["ProductId"].Value == "" ? "0" : orderInfoXacArray["ProductId"].Value);
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：ProductId属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：ProductId属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                      
                        if (pid==0)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：ProductId属性不能为零"));
                            firstUploadQueue.Remark += "err:XML参数：ProductId属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        //T_ProductRelation RelationModel = null;
                        //try
                        //{
                        //   RelationModel=db.T_ProductRelation.FirstOrDefault(p => p.ClientProuctId == pid);
                        //}
                        //catch (Exception ex)
                        //{
                        //    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "未找到对应产品，请确认"));
                        //    firstUploadQueue.Remark += "未找到对应产品，请确认";
                        //    firstUploadQueue.Status = (int)TransferStatus.Error;
                        //    db.SaveChanges();
                        //    return -1;
                        //}
                        //if (RelationModel == null)
                        //{
                        //    throw new Exception("未找到对应产品，请确认");
                        //}
                        Shop_Product_Price product = currShop.Shop_Product_Price.FirstOrDefault(p => p.ProductId == pid);
                        if (product == null)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "客户产品价格已经取消，请确认"));
                            firstUploadQueue.Remark += "客户产品价格已经取消，请确认";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;                                                       
                        }
                        product.Tb_ProductReference.Load();
                        neworder.Tb_Product = product.Tb_Product;
                        try
                        {
                            neworder.OrderProductName = orderInfoXacArray["OrderProductName"].Value + "_" + product.Tb_Product.ProductName;
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：OrderProductName属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：OrderProductName属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }

                        neworder.Width = 0;
                        try
                        {
                            if (string.IsNullOrEmpty(orderInfoXacArray["Width"].Value))
                            {

                            }
                            else
                            {
                               neworder.Width= Convert.ToDouble(orderInfoXacArray["Width"].Value.Trim().ToString());                             
                            }
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：Width属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：Width属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        neworder.Height = 0;
                        try
                        {
                            if (string.IsNullOrEmpty(orderInfoXacArray["Height"].Value))
                            {

                            }
                            else
                            {
                                 neworder.Height= Convert.ToDouble(orderInfoXacArray["Height"].Value.Trim().ToString());                               
                            }
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：Height属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：Height属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        try
                        {
                            neworder.Remark = orderInfoXacArray["Remark"].Value;                            
                        }
                        catch (Exception ex)
                        {
                            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数：Remark属性缺少或不正确"));
                            firstUploadQueue.Remark += "err:XML参数：Remark属性缺少或不正确";
                            firstUploadQueue.Status = (int)TransferStatus.Error;
                            db.SaveChanges();
                            return -1;
                        }
                        neworder.OrderProductCode = "";
                        neworder.IsEdit = false;
                        neworder.PrePriceCount = 0;
                        neworder.ParentProductId = 0;
                        neworder.SinglePageNum = 0;
                        neworder.MultiPageNum = 0;
                        neworder.CompleteTime = newOrderBag.CompleteTime;
                        product.Tb_Product.tb_ProductTypeReference.Load();
                        neworder.ProductType = product.Tb_Product.tb_ProductType.ProductTypeCode;

                        //neworder.CompleteTime
                        ///产品流程
                        //neworder.WorkOrderFlowList = new List<WorkOrderFlowList>();
                        product.Tb_Product.Tb_FlowTemplate.Load();
                        var tempList = product.Tb_Product.Tb_FlowTemplate;
                        int techNum = 0;
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + strOrderproductName + " 写入流程信息"));
                        
                        #region//添加流程
                        DateTime dateNow = DateTime.Now;
                       // foreach (Tb_FlowTemplate temp in tempList.OrderBy(p => p.WorkOrder))
                       List<Tb_FlowTemplate> list=tempList.OrderBy(p => p.WorkOrder).ToList();
                        for(int i=0;i<list.Count();i++)
                        {
                            Tb_FlowTemplate temp=list[i];
                            temp.tb_TechReference.Load();
                            techNum++;
                            
                            WorkOrderFlowList wfl = new WorkOrderFlowList();
                            wfl.tb_Tech = temp.tb_Tech;

                            wfl.AssignTime = dateNow;
                            wfl.ReceiveTime = dateNow;


                            DateTime datetim=dateNow.AddHours(temp.tb_Tech.NeedTime);
                            if (i == 0) {
                                datetim = dateNow;
                            }                            
                            wfl.CompletedTime = datetim;
                            wfl.PreCompleteTime = datetim;

                            dateNow = Convert.ToDateTime(wfl.CompletedTime);

                            wfl.orderInfo = neworder;                         

                            wfl.UserId = 0;
                            wfl.WorkOrder = temp.WorkOrder;
                            if (techNum == 1)
                            {
                                wfl.Status = (int)OrderFlowListStatus.Complete;
                                wfl.UserId = db.users.FirstOrDefault().userID;
                            }
                            else if (techNum == 2)
                            {
                                wfl.Status = (int)OrderFlowListStatus.Useable;
                            }
                            else
                            {
                                wfl.Status = (int)OrderFlowListStatus.Wait;
                            }

                            neworder.WorkOrderFlowList.Add(wfl);

                        }
                        #endregion
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + strOrderproductName + " 写入附加收费项目"));
                        #region//添加收费项目
                        string commItems = "";// orderInfoXacArray["CommonChargeItem"].Value.ToString();
                        currShop.Shop_CommonChargeItem_Price.Load();
                        foreach (string item in commItems.Split('|'))
                        {
                            if (string.IsNullOrEmpty(item))
                            {
                                continue;
                            }
                            int comId = Convert.ToInt32(item);
                            Shop_CommonChargeItem_Price spccip = currShop.Shop_CommonChargeItem_Price.FirstOrDefault(cm => cm.CommonChargeItemId == comId);
                            spccip.CommonChargeItemReference.Load();
                            neworder.CommonChargeItem.Add(spccip.CommonChargeItem);

                        }

                        product.Tb_Product.CommonChargeItem.Load();
                        foreach (CommonChargeItem cci in product.Tb_Product.CommonChargeItem)
                        {
                            if (neworder.CommonChargeItem.Count > 0)
                            {
                                if (neworder.CommonChargeItem.FirstOrDefault(ccip => ccip.CommonChargeItemId == cci.CommonChargeItemId) == null)
                                {
                                    neworder.CommonChargeItem.Add(cci);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        #endregion
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + strOrderproductName + " 写入照片信息"));
                        #region//添加照片
                        double photoAreas = 0;
                        //产品照片列表
                        XmlNodeList xmPhotoList = orderNode.ChildNodes;
                        foreach (XmlNode photoNode in xmPhotoList)
                        {
                            XmlAttributeCollection photoAttriArry = photoNode.Attributes;
                            photoInfo photo = new photoInfo();

                            try
                            {
                                photo.photoName = photoAttriArry["photoName"].Value;
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：photoName属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：photoName属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }

                            try
                            {
                                photo.Height = Convert.ToDouble(photoAttriArry["Height"].Value);
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：Height属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：Height属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.IsModifySize = false;
                            try
                            {
                                photo.picPath = photoAttriArry["picPath"].Value;
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：picPath属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：picPath属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.OldPicPath = orderOrilPath +photo.picPath.Replace("/",@"\");
                            

                            photo.orderInfo = neworder;
                            //int faceid = Convert.ToInt32(photoAttriArry["paperFaceId"].Value);
                           // int faceid = Convert.ToInt32(photoAttriArry["paperFaceId"].Value==""?"0":photoAttriArry["paperFaceId"].Value);

                            photo.paperFace = db.paperFace.FirstOrDefault();

                            currShop.Shop_Paper_Price.Load();

                             int paperTypeid =0;
                            try
                            {
                                paperTypeid = Convert.ToInt32(photoAttriArry["paperTypeID"].Value == "" ? "0" : photoAttriArry["paperTypeID"].Value);
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：paperTypeID属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：paperTypeID属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            Shop_Paper_Price spp = currShop.Shop_Paper_Price.FirstOrDefault(pt => pt.PaperTypeId == paperTypeid);
                            if (spp == null)
                            {
                                throw new Exception("客户纸型价格已经取消或者未定义，请确认");
                            }
                            else
                            {
                                photo.paperType = db.paperType.FirstOrDefault(pt => pt.PaperTypeID == spp.PaperTypeId);
                            }
                            photo.PhotoBarCode = "";
                            try
                            {
                                photo.picPath = photoAttriArry["picPath"].Value;
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：picPath属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：picPath属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.Remark = "";
                            try
                            {
                                photo.Remark = photoAttriArry["picPath"].Value;
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：picPath属性缺少或不正确"));
                                return -1;
                            }
                            photo.pixHeight = 0;
                            try
                            {
                                if (string.IsNullOrEmpty(photoAttriArry["Pixheight"].Value))
                                {

                                }
                                else
                                {
                                    double dou = Convert.ToDouble(photoAttriArry["Pixheight"].Value.Trim().ToString());
                                    photo.pixHeight = Convert.ToInt32(dou);
                                }
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：Pixheight属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：Pixheight属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.pixWidth = 0;
                            try
                            {

                                if (string.IsNullOrEmpty(photoAttriArry["pixWidth"].Value))
                                {

                                }
                                else
                                {
                                    double dou = Convert.ToDouble(photoAttriArry["pixWidth"].Value.Trim().ToString());
                                    photo.pixWidth = Convert.ToInt32(dou);
                                }
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：pixWidth属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：pixWidth属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.printerId = 0;
                            photo.status = (int)PhotoStatus.NoDistributePrinter;
                            photo.status2 = (int)PhotoStatus2.normal;
                            photo.TotalNum = 0;
                            try
                            {
                                if (string.IsNullOrEmpty(photoAttriArry["TotalNum"].Value))
                                {

                                }
                                else
                                {
                                    double dou = Convert.ToDouble(photoAttriArry["TotalNum"].Value.Trim().ToString());
                                    photo.TotalNum = Convert.ToInt32(dou);
                                }
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：TotalNum属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：TotalNum属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photo.userId = 0;
                            try
                            {
                                if (string.IsNullOrEmpty(photoAttriArry["Width"].Value))
                                {

                                }
                                else
                                {
                                    photo.Width = Convert.ToDouble(photoAttriArry["Width"].Value.Trim().ToString());
                                }
                            }
                            catch (Exception ex)
                            {
                                AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "XML参数产品照片列表：Width属性缺少或不正确"));
                                firstUploadQueue.Remark += "err:XML参数产品照片列表：Width属性缺少或不正确";
                                firstUploadQueue.Status = (int)TransferStatus.Error;
                                db.SaveChanges();
                                return -1;
                            }
                            photoAreas += (double)(photo.Width * photo.Height * 2.54 * 2.54 / 10000 * photo.TotalNum);
                            //创建photo时拷贝文件
                            if (neworder.photoInfo == null)
                            {
                                neworder.photoInfo = new System.Data.Objects.DataClasses.EntityCollection<photoInfo>();
                            }
                            neworder.photoInfo.Add(photo);
                        }
                        #endregion
                        ///计算每日开单面积
                        ///预计算价格
                        //db.AddToTb_OrderBag(newOrderBag);
                        neworder.Area = neworder.productNum * photoAreas;
                        newOrderBag.orderInfo.Add(neworder);

                    }///产品循环
                     ///
                    db.AddToTb_OrderBag(newOrderBag);
                    db.SaveChanges();
                                      

                    string OrderBagPath = ShopSaveCurrPath + "\\" + newOrderBag.OrderBagId + "_" + newOrderBag.BagName;

                    if (!Directory.Exists(OrderBagPath))
                    {
                        Directory.CreateDirectory(OrderBagPath);
                    }
                    int picOrder = 1;

                    #region   //更新orderinfo、photoinfo、tb_orderbag中的对应的CODE统计开单面积,拷贝照片
                    foreach (var oi in newOrderBag.orderInfo)
                    {

                        string orderproductPath = Path.Combine(OrderBagPath, oi.CtmName,oi.OrderProductName); // + "\\" + +"\\" + ;
                        string orderproductBackPath = Path.Combine(OrderBagPath, oi.CtmName, oi.OrderProductName,"Backup");

                        orderproductPath = orderproductPath.Replace('*', '_');
                        orderproductBackPath = orderproductBackPath.Replace('*','_');                        
                        if (!Directory.Exists(orderproductPath))
                        {
                            Directory.CreateDirectory(orderproductPath);
                        }
                        if (!Directory.Exists(orderproductBackPath))
                        {
                            Directory.CreateDirectory(orderproductBackPath);
                        }
                        oi.OrderPath = orderproductPath;//设置产品路径
                        oi.OrderProductCode = "2" + oi.OrderProductId.ToString().PadLeft(9, '0');
                        oi.status = (int)OrderInfoStatus.Doing;
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + oi.OrderProductName + " 复制照片"));

                        foreach (var pi in oi.photoInfo)
                        {
                            pi.PhotoBarCode = "3" + pi.photoId.ToString().PadLeft(9, '0');

                            string picPath = orderproductPath + "\\" + newOrderBag.OrderBagId + "_" + picOrder + "_" + pi.photoName;

                            string picBackPath = orderproductBackPath + "\\" + pi.photoName;
                            pi.picPath = picPath;

                            //FileOperate.CopyFileA(pi.OldPicPath, picBackPath, true);//先复制到备份文件夹
                            File.Copy(pi.OldPicPath, picBackPath, true);
                            FileOperate.MoveFile(pi.OldPicPath, picPath, 2);
                            picOrder++;
                        }
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + oi.OrderProductName + " 计算价格"));

                        SataShopProductAndOrderArea(oi, db, oi.Area);//统计开单面积开单产品等
                        Bill_Detail bd = new Bill_Detail();
                        oi.PrePriceCount = BillBLL.GetOrderPrice(currShop, oi, db, bd);//预计产品价格
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在为产品 " + oi.OrderProductName + " 写入产品状态"));

                        BillBLL.CheckOrderCount(oi, currShop, true, db);


                    }
                    newOrderBag.BagCode = "1" + newOrderBag.OrderBagId.ToString().PadLeft(9, '0');
                    newOrderBag.Status = (int)OrderBagStatus.Doing;
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, firstUploadQueue.ZipName + "正在保存"));
                    firstUploadQueue.Status = (int)TransferStatus.AnlyseComplete;
                    firstUploadQueue.orderbagid = newOrderBag.OrderBagId;

                    //更改订单取件时间
                    try
                    {
                        Tb_OrderBag bag = newOrderBag;
                        List<orderInfo> list = bag.orderInfo.ToList();
                        //List<WorkOrderFlowList> flowlist = bag.orderInfo.WorkOrderFlowList.ToList();
                        Dictionary<int, double> diclist = new Dictionary<int, double>();  //key  表示产品，double 表示当前产品所需要的时间
                        //foreach (WorkOrderFlowList item in flowlist)
                        //{
                        //    if (!item.orderInfoReference.IsLoaded)
                        //    {
                        //        item.orderInfoReference.Load();
                        //    }
                        //}
                        foreach (orderInfo er in list)  //
                        {
                            List<WorkOrderFlowList> flow = er.WorkOrderFlowList.ToList();
                            foreach (WorkOrderFlowList fl in flow)
                            {
                                double dou = fl.tb_Tech.NeedTime;
                                if (diclist.ContainsKey(er.OrderProductId))
                                {
                                    diclist[er.OrderProductId] += dou;
                                }
                                else
                                {
                                    diclist.Add(er.OrderProductId, dou);
                                }
                            }
                        }
                        diclist.OrderByDescending(d => d.Value).Select(d => d.Key).First();
                     
                        double minkey = diclist.Keys.Cast<int>().Select(x => new { x, y = diclist[x] }).OrderByDescending(x => x.y).First().y;                       
                       bag.FetchTime= bag.OrderTime.AddHours(minkey); //开单时间加上最长一个产品所需要的时间，等于取件时间
                       
                        db.SaveChanges();//保存这个取件时间
                    }
                    catch (Exception ex)
                    {
                        AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, "保存取件时间失败"));
                        return -1;
                    }

                    #endregion

                    #region//正常开单结束后备份压缩删除解压文件
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, "正在删除临时文件"));
                    //删除文件
                    if (File.Exists(workZipPath))
                    {
                        File.Delete(workZipPath);
                    }
                    string DelDir = workZipPath.Substring(0, workZipPath.LastIndexOf("."));
                    if (Directory.Exists(DelDir))
                    {
                        Directory.Delete(DelDir, true);
                    }

                    #endregion
                }//数据连接结束
            }
            catch(Exception exs)//处理不预期的异常
            {
                using (newSampleYPDBEntities edb = new newSampleYPDBEntities())
                {
                    UploadQueue uqE = edb.UploadQueue.FirstOrDefault(u => u.UploadId == uqid);
                    uqE.Status = (int)TransferStatus.Error;
                    uqE.Remark = exs.Message;
                    edb.SaveChanges();
                    AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Error, uqE.ZipName + "错误" + exs.Message));
                    return -1;
                }

            }
            AnalysEventMonitor.Send(new AnalysInfoEventArgs(DateTime.Now, EventType.Normal, "<=======订单完成======>"));
            return 1;

        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        private DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }
       

        /// <summary>
        /// 统计开单面积
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="dataBase"></param>
        /// <param name="PhotoAreas"></param>
        private void SataShopProductAndOrderArea(orderInfo oi, newSampleYPDBEntities dataBase, double PhotoAreas)//统计商户的开单产品和开单面积
        {
            if (!oi.Tb_ProductReference.IsLoaded)
                oi.Tb_ProductReference.Load();

            if (!oi.Tb_OrderBagReference.IsLoaded)
                oi.Tb_OrderBagReference.Load();

            if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                oi.Tb_OrderBag.ShopReference.Load();

            #region 商户下单产品统计

            string strSpc = oi.Tb_Product.Width + "*" + oi.Tb_Product.Height;
            ShopProduct sp = dataBase.ShopProduct.FirstOrDefault(p => p.ShopName == oi.Tb_OrderBag.Shop.shopName && p.ProductName == oi.Tb_Product.ProductName && p.Spec == strSpc && p.OrderTime == oi.Tb_OrderBag.OrderTime.Date);

            if (sp == null)//添加新的
            {
                ShopProduct spNew = new ShopProduct()
                {
                    Area = PhotoAreas,
                    OrderTime = oi.Tb_OrderBag.OrderTime.Date,
                    ProductName = oi.Tb_Product.ProductName,
                    ProductNum = 1,
                    ShopName = oi.Tb_OrderBag.Shop.shopName,
                    Spec = oi.Tb_Product.Width + "*" + oi.Tb_Product.Height
                };
                dataBase.AddToShopProduct(spNew);
            }
            else
            {
                sp.Area += PhotoAreas;
                sp.ProductNum++;
            }

            #endregion

            #region 每日开单面积统计

            CreateOrderAreaByDay orderArea = dataBase.CreateOrderAreaByDay.FirstOrDefault(d => d.CreateOrderDate == oi.Tb_OrderBag.OrderTime.Date && d.AreaName == oi.Tb_OrderBag.Shop.Area && d.ShopName == oi.Tb_OrderBag.Shop.shopName);
            if (orderArea == null)
            {
                CreateOrderAreaByDay newDay = new CreateOrderAreaByDay()
                {
                    CreateOrderDate = oi.Tb_OrderBag.OrderTime.Date,
                    Area = PhotoAreas,
                    ShopName = oi.Tb_OrderBag.Shop.shopName,
                    AreaName = oi.Tb_OrderBag.Shop.Area
                };
                dataBase.AddToCreateOrderAreaByDay(newDay);
            }
            else
            {
                orderArea.Area += PhotoAreas;
            }
            #endregion

            #region
            Shop currShop = oi.Tb_OrderBag.Shop;
            currShop.Shop_Product_Price.Load();
            Shop_Product_Price spp = currShop.Shop_Product_Price.FirstOrDefault(s=>s.ProductId==oi.Tb_Product.ProuctId);
            spp.usedTimes++;
            #endregion


        }
        public void Start()
        {
            _IsRuning = false;
            timeAnalyse.Enabled = true;
            //AnalyseOrder();
        }
        

    }
}
